package day02;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoGetFilePath extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ServletContext context = getServletContext();
		
		// 获取项目部署的真实路径
		String filePath = context.getRealPath("/");
		
		System.out.println(filePath);
		
		// 场景①：读取src下面的文件：方式一
		String file1 = context.getRealPath("/WEB-INF/classes/resources/db.config");
		System.out.println(file1);
		
		// 查看文件是否存在
		File file = new File(file1);
		System.out.println("文件是否存在：" + file.exists());
		
		// 读取文件内容
		BufferedReader reader = new BufferedReader(new FileReader(file));
		System.out.println(reader.readLine());
		reader.close();
		
		// 场景①：读取src下面的文件方式二
		URL resource = getClass().getResource("../resources/db.config");
		try {
			System.out.println(new File(resource.toURI()).exists());
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		
		// 场景②：读取WebContent下面的文件
		String file2 = context.getRealPath("/2.txt");
		reader = new BufferedReader(new FileReader(file2));
		System.out.println(reader.readLine());
		
		
		
	}
}
